package com.zyy.study.always.code4;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

public class Bank {

    private Map<String,BankAccount> accounts=new HashMap<>();

    public void createAccount(String id, String name, double money) {
        BankAccount bankAccount = new BankAccount(id, new BigDecimal(money), name);
        accounts.put(id, bankAccount);
    }

    public BankAccount getAccount(String id) {
        BankAccount bankAccount = accounts.get(id);
        return bankAccount;
    }

    public void printAllBalances() {
        accounts.forEach((key, value) -> {
            System.out.println(value.toString());
        });
    }
    public void transfer(BankAccount from, BankAccount to, double amount) {
        // 实现转账逻辑
        synchronized (from) {
            if (from.validateWithdraw(new BigDecimal(amount))) {
                synchronized (to) {
                    if (to.validateDeposit(new BigDecimal(amount))) {
                        from.withdraw(amount);
                        to.deposit(amount);
                        from.updateWithdraw(new BigDecimal(amount));
                        to.updateDeposit(new BigDecimal(amount));
                    }
                }
            }
        }
    }
    // 添加账户冻结/解冻功能
    public void freezeAccount(String accountId){
        accounts.get(accountId).setActive(true);
    }
    public void unfreezeAccount(String accountId){
        accounts.get(accountId).setActive(false);
    }
}
